#include <WiFi.h>
#include "PubSubClient.h"
#include "string.h"
#include<stdlib.h> 



/* 连接WIFI SSID和密码 */
#define WIFI_SSID         ""
#define WIFI_PASSWD       ""



/* 线上环境域名和端口号，不需要改 */
#define MQTT_SERVER       "10.10.42.56"
#define MQTT_PORT         1883
#define MQTT_USRNAME      "mac"

#define CLIENT_ID         "6kYp6jszrDns2yh4_baojin_asd"
#define MQTT_PASSWD       	"6f1cd954579559bfdcd0b58965a76091"


#define ALINK_BODY_FORMAT         "{\"id\":\"16642880205090mac000000000006b\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST     "/sys/6kYp6jszrDns2yh4/mac/s/event/property/post"

unsigned long lastMs = 0;
float soil_data ;  
float tep; 
WiFiClient espClient;
PubSubClient  client(espClient);
//连接wifi
void wifiInit()
{
    WiFi.begin(WIFI_SSID, WIFI_PASSWD);
    while (WiFi.status() != WL_CONNECTED)
    {
      ;
        delay(1000);
        Serial.println("WiFi not Connect");
    }
    
}
//mqtt连接
void mqttCheckConnect()
{
    while (!client.connected())
    {
        Serial.println("Connecting to MQTT Server ...");
        if(client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
        {
          ;
          Serial.println("MQTT Connected!");
        }
        else{
      
           Serial.print("MQTT Connect err:");
         Serial.println(client.state());
            delay(5000);

          }
        
    }
}

void mqttIntervalPost()
{
    char param[32];
    char jsonBuf[128];
    
    soil_data ++;   
    sprintf(param, "{\"humidity\":%2f}", soil_data);
    sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
    
    boolean b = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);

    tep =20.3;
    sprintf(param, "{\"temperature\":%2f}",tep);
    sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
    Serial.println(jsonBuf);
    boolean c = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);

   
}


void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);   // 打印主题信息
  Serial.print("] ");

  for (int i = 0; i < length; i++) {
      Serial.print((char)payload[i]); // 打印主题内容 

  }

    Serial.println();
}
void setup() 
{
    Serial.begin(115200);
   // Serial2.begin(500000);
    wifiInit();
   
    client.setServer(MQTT_SERVER, MQTT_PORT);   /* 连接MQTT服务器 */
  
 
    client.setCallback(callback); 
}

void loop()
{


    client.subscribe("/sys/6kYp6jszrDns2yh4/mac/c/#");
  
 
   
        mqttCheckConnect(); 
        /* 上报 */
        mqttIntervalPost();

    client.loop();
    delay(20);
}
